<template>
  <view class="pending-container">
    <!-- 加载状态 -->
    <uni-load-more v-if="loading" status="loading"></uni-load-more>
    
    <!-- 无订单提示 -->
    <view v-else-if="orders.length === 0" class="empty-orders">

      <text>暂无待付款订单</text>
      <view class="action-buttons">
        <button type="primary" class="goto-shop" @tap="goToShop">去逛逛</button>
        <button type="default" class="refresh-btn" @tap="fetchPendingOrders">刷新</button>

      </view>
    </view>
    
    <!-- 订单列表 -->
    <view v-else class="order-list">
      <view 
        v-for="order in orders" 
        :key="order._id" 
        class="order-item"
      >
        <view class="order-header">
          <text class="order-no">订单号: {{ order.order_no }}</text>
          <text class="order-status">{{ getStatusText(order.status) }}</text>
        </view>
        
        <view class="order-products">
          <view 
            v-for="(product, index) in order.products" 
            :key="index"
            class="product-item"
          >
            <image :src="url('sp', product.image-1, 'png')" class="product-image" mode="aspectFill"></image>
       
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <view class="product-specs" v-if="product.specs && Object.keys(product.specs).length">
                <text>规格: {{ formatSpecs(product.specs) }}</text>
              </view>
              <view class="product-price-qty">
                <text class="product-price">¥{{ product.price.toFixed(2) }}</text>
                <text class="product-qty">x{{ product.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="order-footer">
          <view class="order-total">
            <text>总计: </text>
            <text class="total-price">¥{{ order.total_price.toFixed(2) }}</text>
          </view>
          
          <view class="order-actions">
            <button class="action-btn cancel-btn" @tap="cancelOrder(order._id)">取消订单</button>
            <button class="action-btn pay-btn" @tap="payOrder(order)">立即付款</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useUserStore } from '@/stores/userStore';

const userStore = useUserStore();
const url = $url;
const loading = ref(true);
const orders = ref([]);

// 获取待付款订单
const fetchPendingOrders = async () => {
  loading.value = true;
  
  try {
    console.log('开始获取待付款订单...');
    
    // 确保用户已登录
    if (!userStore.isLoggedIn || !userStore.userInfo || !userStore.userInfo.account) {
      console.error('用户未登录，无法获取订单');
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      loading.value = false;
      return;
    }
    
    // 使用 userStore 中的 getOrdersByStatus 方法获取待付款订单
    orders.value = await userStore.getOrdersByStatus('pending');
    console.log('获取到的待付款订单:', orders.value);
    
  } catch (error) {
    console.error('获取待付款订单失败:', error);
    uni.showToast({
      title: error.message || '获取订单失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 格式化规格
const formatSpecs = (specs) => {
  if (!specs) return '';
  return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ');
};

// 获取状态文字
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'unpaid': '待发货',
    'shipping': '已发货',
    'received': '已收货',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return statusMap[status] || status;
};

// 取消订单
const cancelOrder = async (orderId) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: async (res) => {
      if (res.confirm) {
        const success = await userStore.updateOrderStatus(orderId, 'cancelled');
        if (success) {
          uni.showToast({
            title: '订单已取消',
            icon: 'success'
          });
          // 重新获取订单列表
          fetchPendingOrders();
        }
      }
    }
  });
};

// 支付订单
const payOrder = (order) => {
  uni.showModal({
    title: '支付',
    content: `确认支付¥${order.total_price.toFixed(2)}?`,
    success: async (res) => {
      if (res.confirm) {
        const success = await userStore.updateOrderStatus(order._id, 'unpaid');
        if (success) {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          });
          
          setTimeout(() => {
            // 跳转到待发货页面
            uni.navigateTo({
              url: '/pages/my/order-types/unpaid'
            });
          }, 1500);
        }
      }
    }
  });
};

// 跳转到商城页面
const goToShop = () => {
  uni.switchTab({
    url: '/pages/shop/index'
  });
};



onMounted(async () => {
  // 检查用户是否登录
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    });
    
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/other/login'
      });
    }, 2000);
    return;
  }
  
  // 加载订单数据
  await fetchPendingOrders();
});
</script>

<style scoped>
.pending-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20rpx;
}

.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-top: 30rpx;
  width: 240rpx;
}

.goto-shop, .refresh-btn, .init-btn {
  font-size: 28rpx;
}

.order-list {
  padding-bottom: 100rpx;
}

.order-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.order-no {
  font-size: 28rpx;
  color: #666;
}

.order-status {
  font-size: 28rpx;
  color: var(--td-brand-color);
  font-weight: bold;
}

.order-products {
  padding: 20rpx 30rpx;
}

.product-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f9f9f9;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;

  margin-right: 20rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.product-specs {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.product-price-qty {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.product-qty {
  font-size: 26rpx;
  color: #999;
}

.order-footer {
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.order-total {
  text-align: right;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.total-price {
  font-weight: bold;
  color: var(--td-brand-color);
  font-size: 32rpx;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.action-btn {
  padding: 16rpx 30rpx;
  font-size: 26rpx;
  border-radius: 60rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.pay-btn {
  background-color: var(--td-brand-color);
  color: #fff;
}
</style> 